package cn.zn.wx.security.service.impl;

import cn.zn.framework.security.inter.service.MySecurityService;
import cn.zn.framework.security.inter.vo.LoginUserVO;
import cn.zn.modules.zzsys.inter.vo.SysUserVO;
import cn.zn.wx.security.vo.MyUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zn
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService, MySecurityService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserVO sysUserVO = null;
        if (sysUserVO == null) {
            throw new UsernameNotFoundException("");
        }
        MyUserDetails myUserDetails = MyUserDetails.builder().build();
        BeanUtils.copyProperties(sysUserVO, myUserDetails);
        myUserDetails.setAccountNonExpired(true);
        myUserDetails.setAccountNonLocked(true);
        myUserDetails.setCredentialsNonExpired(true);
        myUserDetails.setEnabled(true);
        return myUserDetails;
    }

    @Override
    public LoginUserVO loginUser() {
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        MyUserDetails myUserDetails = (MyUserDetails) authentication.getPrincipal();
        LoginUserVO loginUserVO = LoginUserVO.builder().build();
        BeanUtils.copyProperties(myUserDetails, loginUserVO);
        return loginUserVO;
    }

    @Override
    public String passwordEncoder(String password) {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(password);
    }

    @Override
    public Boolean passwordMatches(String password1, String password2) {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder().matches(password1, password2);
    }

    @Override
    public String passwordEncoderMD5(String password) {
        PasswordEncoder passwordEncoder = new MessageDigestPasswordEncoder("MD5");
        return passwordEncoder.encode(password);
    }
}
